import "./Index.css";
import * as echarts from 'echarts';
import { useEffect, useState, useMemo } from 'react';
import { Progress, Tabs, Typography, Button, Image } from '@arco-design/web-react';
import { IconLeft, IconRight } from '@arco-design/web-react/icon';
import api from '../../API/indexApi'
const Index = () => {
  useEffect(() => {
    // 图表
    realTimeData();
    // api--------------
    getTotalIncome();
    getYoyWeekly();
    getDayOnMonth();
    getDayIncome();
    getTotalFlow();
    getDayFlow();
    getEtcPayNum();
    getUtilizationRate();
    getOccupancy();
    getParkingLotRise();
    getParkingLotFall();
    // ---图表api
    getPaymentMethod();
    getDailyIncome();
    getEtcCharts();
    getParkingCharts();
  }, [])
  // 停车数据图表
  const parkingCharts = () => {
    let myChart = echarts.init(document.getElementById('parkingChart'));
    myChart.setOption({
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          show: false, // 不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
          axisTick: {
            show: false // 不显示坐标轴刻度线
          },
          axisLine: {
            show: false, // 不显示坐标轴线
          },
          axisLabel: {
            show: false, // 不显示坐标轴上的文字
          },
          splitLine: {
            show: false // 不显示网格线
          },
          data: parkingChartsTit
        }

      ],
      yAxis: [
        {
          type: 'value',
          boundaryGap: [0, '30%'],
          boundaryGap: false,
          show: false, // 不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
          axisTick: {
            show: false // 不显示坐标轴刻度线
          },
          axisLine: {
            show: false, // 不显示坐标轴线
          },
          axisLabel: {
            show: false, // 不显示坐标轴上的文字
          },
          splitLine: {
            show: false // 不显示网格线
          },
        }


      ],
      visualMap: {
        type: 'piecewise',
        show: false,
        dimension: 0,
        seriesIndex: 0,
      },
      series: [
        {
          type: 'line',
          smooth: 0.6,
          symbol: 'none',
          lineStyle: {
            color: '#5470C6',
            width: 5
          },
          markLine: {
            symbol: ['none', 'none'],
            label: { show: false },
            data: [{ xAxis: 1 }, { xAxis: 3 }, { xAxis: 5 }, { xAxis: 7 }]
          },
          areaStyle: {},
          data: parkingChartsVal
        }
      ]
    });
  }

  // ETC图表
  const EtcCharts = () => {
    let myChart = echarts.init(document.getElementById('main'));
    myChart.setOption({
      tooltip: {},
      xAxis: [
        {
          data: EtcChartsTit,
          boundaryGap: false,
          show: false, // 不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
          axisTick: {
            show: false // 不显示坐标轴刻度线
          },
          axisLine: {
            show: false, // 不显示坐标轴线
          },
          axisLabel: {
            show: false, // 不显示坐标轴上的文字
          },
          splitLine: {
            show: false // 不显示网格线
          },
        }
      ],
      yAxis: [
        {
          boundaryGap: false,
          show: false, // 不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
          axisTick: {
            show: false // 不显示坐标轴刻度线
          },
          axisLine: {
            show: false, // 不显示坐标轴线
          },
          axisLabel: {
            show: false, // 不显示坐标轴上的文字
          },
          splitLine: {
            show: false // 不显示网格线
          },
        }
      ],
      series: [
        {
          type: 'bar',
          data: EtcChartsVal
        }
      ]
    });
  }
  // 日收入趋势图表
  const dailyIncome = () => {
    let myChart = echarts.init(document.getElementById('dailyIncome'));
    // 绘制图表
    myChart.setOption({
      title: {
        text: '日收入趋势'
      },
      tooltip: {},
      xAxis: [
        {
          data: dailyIncomeTit,
        }
      ],

      yAxis: {},
      series: [
        {
          name: '销量',
          type: 'bar',
          data: dailyIncomeVal
        }
      ]
    });
  }
  // 支付方式图表
  const PaymentMethod = () => {
    let myChart = echarts.init(document.getElementById('PaymentMethod'));
    let data = paymentData
    let totalCount = data.reduce((vs, v) => vs + v.value, 0);
    let formatNumber = (num) => num.toString().replace(/(?=(\B)(\d{3})+$)/g, ',');
    // 绘制图表
    myChart.setOption({
      title: [
        {
          text: `{name|停车收入}\n{val|￥${formatNumber(totalCount)}}`,
          top: 'center',
          left: 'center',
          textStyle: {
            rich: {
              name: {
                fontSize: 14,
                color: '#666666',
                padding: [10, 0]
              },
              val: {
                fontSize: 22,
                fontWeight: 'bold',
                color: '#333333'
              }
            }
          }
        },
        {
          text: '支付方式',
          top: 20,
          left: 'center',
          textStyle: { fontSize: 14, color: '#666666', fontWeight: 400 }
        }
      ],
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(0,0,0,0.9)',
        formatter: (params) => `${params.data.name}<br/>
        ${params.marker}<span style="color:${params.color}">停车收入: ${params.value}</span>`
      },
      series: {
        type: 'pie',
        radius: [80, 50],
        left: 'center',
        top: 'center',
        width: 400,
        itemStyle: { borderColor: '#fff', borderWidth: 1 },
        label: {
          alignTo: 'edge',
          formatter: '{name|{b}}\n{value|{d}% - {c}元}',
          minMargin: 5,
          edgeDistance: 10,
          lineHeight: 15,
          rich: { value: { fontSize: 10, color: '#999999' } }
        },
        labelLine: {
          length: 15,
          length2: 0,
          maxSurfaceAngle: 80
        },
        labelLayout: (params) => {
          const isLeft = params.labelRect.x < myChart.getWidth() / 2;
          const points = params.labelLinePoints;
          points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
          return params;
        },
        data: data
      }
    });
  }
  // 实时停车数据图表
  const realTimeData = () => {

    // 实时数据方案一--------------------

    let myChart = echarts.init(document.getElementById('realTimeData'));
    let data = [24, 17, 20, 25, 12]
    let data2 = [90, 80, 50, 100, 22]
    let timeData = ["10:00", "11:00", "12:00", "13:00", "14:00"]
    let option = {
      title: {
        text: "实时数据",
        textStyle: {
          color: "#000"
        }
      },
      tooltip: {  // 鼠标悬停到图表上时的提示框

      },
      xAxis: { // 柱状图的横坐标 (每一个商品分类)
        name: "实时数据",
        nameLocation: "center",
        nameGap: 30,
        data: timeData
      },
      yAxis: { // 柱状图的纵坐标 (每一个分类的商品数量)
        name: "流量",
        min: 10
        // max: 100
      },
      legend: {  // 图表系列标记, 一定要和系列名对应
        data: ["车流量/辆"],
        // 自定义系列标记
        // icon: "image://item273.png",
        // itemWidth: 14  // 图标宽度
        textStyle: {
          color: 'white'
        },
        inactiveColor: "gray"
      },
      series: [  // 图表类型和数据 (每一个对象是一个图表)
        {
          name: "车流量/辆",  // 图表系列名
          type: "line",   // 图表类型 line折线图
          data: data,  // 图表数据,
          lineStyle: {
            width: 3,
            color: '#4CA9FF'
          }
        },
        {
          name: "交易金额",  // 图表系列名
          type: "line",   // 图表类型 line折线图
          data: data2,  // 图表数据,
          lineStyle: {
            width: 3,
            color: '#2FC25B'
          }
        }
      ]

    }
    myChart.setOption(option);
    setInterval(() => {
      const randomNum = parseInt(Math.random() * 100)
      data.push(randomNum)
      data2.push(randomNum * 3.5)
      timeData.push(String(new Date().getHours()) + ':' + String(new Date().getMinutes()) + ':' + String(new Date().getSeconds()))
      myChart.setOption(option)
    }, 3000);

    // 实时数据方案二--------------------
    // let myChart = echarts.init(document.getElementById('realTimeData'));
    // function randomData () {
    //   now = new Date(+now + oneDay);
    //   value = value + Math.random() * 21 - 10;
    //   return {
    //     name: now.toString(),
    //     value: [
    //       [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
    //       Math.round(value)
    //     ]
    //   };
    // }
    // let data = [];
    // let now = new Date(2018, 1, 1);
    // let oneDay = 24 * 3600 * 1000;
    // let value = Math.random() * 1000;
    // for (var i = 0; i < 1000; i++) {
    //   data.push(randomData());
    // }
    // let option = {
    //   title: {
    //     text: 'Dynamic Data & Time Axis'
    //   },
    //   tooltip: {
    //     trigger: 'axis',
    //     formatter: function (params) {
    //       params = params[0];
    //       var date = new Date(params.name);
    //       return (
    //         date.getDate() +
    //         '/' +
    //         (date.getMonth() + 1) +
    //         '/' +
    //         date.getFullYear() +
    //         ' : ' +
    //         params.value[1]
    //       );
    //     },
    //     axisPointer: {
    //       animation: false
    //     }
    //   },
    //   xAxis: {
    //     type: 'time',
    //     splitLine: {
    //       show: false
    //     }
    //   },
    //   yAxis: {
    //     type: 'value',
    //     boundaryGap: [0, '100%'],
    //     splitLine: {
    //       show: false
    //     }
    //   },
    //   series: [
    //     {
    //       name: 'Fake Data',
    //       type: 'line',
    //       showSymbol: false,
    //       data: data
    //     }
    //   ]
    // };
    // setInterval(function () {
    //   // console.log(randomData());
    //   console.log(oneDay);
    //   data.shift();
    //   data.push(randomData());
    //   myChart.setOption(option);
    // }, 1000);
  }
  // 访问量图表
  const visits = () => {
    let myChart = echarts.init(document.getElementById('visits'));
    let option = {
      xAxis: {
        type: 'category',
        data: visitsTit
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: visitsVal,
          type: 'line',
          smooth: true
        }
      ]
    }
    myChart.setOption(option);
  }
  // 停车收入数据----------------
  const [totalRevenue, setTotalRevenue] = useState('12600')//停车总收入
  const [rise, setRise] = useState(0)//周同比
  const [fall, setFall] = useState(0)//日环比
  const [dayIncome, setDayIncome] = useState(0)//日均收入

  // 车流量数据------------------
  const [totalFlow, setTotalFlow] = useState(0)
  const [dayVisits, setDayVisits] = useState(0)
  // ETC数据
  const [totalETC, setTotalETC] = useState(0)//ETC总笔数
  const [utilizationRate, setUtilizationRate] = useState(0)//使用率
  // 车位数据--------------------
  const [occupancy, setOccupancy] = useState(0)//占用率
  // 车位周同比
  const [parkingLotRise, setParkingLotRise] = useState(0)
  // 车位日环比
  const [parkingLotFall, setParkingLotFall] = useState(0)

  // =================图表数据========================
  // 车流量图表数据
  const parkingChartsTit = []//车流量图表title
  const parkingChartsVal = []//车流量图表value
  // ETC图表数据
  const EtcChartsTit = []//ETC图表title
  const EtcChartsVal = []//ETC图表value
  // 日收入趋势图表数据-----
  const dailyIncomeTit = []//日收入趋势title
  const dailyIncomeVal = []//日收入趋势value
  // 访问量图表数据
  const visitsTit = []//访问量图表title
  const visitsVal = []//访问量图表value
  // 监控数据-------------------
  const monitor = {
    monitorA: 32
  }
  // tab开关控制项
  let tabSwitch = 0;
  // 支付方式图表数据
  let paymentData = [
    { value: 3035, name: 'ETC' },
    { value: 532, name: '现金' },
    { value: 5763, name: '支付宝' },
    { value: 1091, name: '银联' },
    { value: 300, name: '京东' },
    { value: 5875, name: '微信' }
  ]
  // 流量数据
  const onTable = (key) => {
    tabSwitch++;
    if (key === '2' && tabSwitch == 1) {
      getVisits();
    }
  }
  // tab选项卡
  const TabPane = Tabs.TabPane;
  const style = {
    textAlign: 'center',
    marginTop: 20,
  };
  // -------------------API---------------------------------------------------------------------------------
  // -----获取总停车收入
  const getTotalIncome = () => {
    api.getTotalIncome().then(res => {
      if (res.code === 200) {
        console.log(res);
        setTotalRevenue(res.result.data)
      }
    })
  }
  // -----获取周同比
  const getYoyWeekly = () => {
    api.getYoyWeekly().then(res => {
      if (res.code === 200) {
        setRise(res.result.data)
      }
    })
  }
  // -----获取日环比
  const getDayOnMonth = () => {
    api.getDayOnMonth().then(res => {
      if (res.code === 200) {
        if (res.result !== null && res.result !== '' && res.result !== undefined) {
          setFall(res.result.data)
        }
      }
    })
  }
  // -----获取日均收入
  const getDayIncome = () => {
    api.getDayIncome().then(res => {
      if (res.code === 200) {
        setDayIncome(res.result.date)
      }
    })
  }
  // -----获取车流量
  const getTotalFlow = () => {
    api.getTotalFlow().then(res => {
      if (res.code === 200) {
        setTotalFlow(res.result.data)
      }
    })
  }
  // -----获取日访问量
  const getDayFlow = () => {
    api.getDayFlow().then(res => {
      if (res.code === 200) {
        setDayVisits(res.result.data)
      }
    })
  }
  // -----获取ETC支付笔数
  const getEtcPayNum = () => {
    api.getEtcPayNum().then(res => {
      if (res.code === 200) {
        setTotalETC(res.result.data)
      }
    })
  }
  // -----获取ETC支付笔数
  const getUtilizationRate = () => {
    api.getUtilizationRate().then(res => {
      if (res.code === 200) {
        setUtilizationRate(res.result.data)
      }
    })
  }
  // -----获取车位占用率
  const getOccupancy = () => {
    api.getOccupancy().then(res => {
      if (res.code === 200) {
        setOccupancy(res.result.data)
      }
    })
  }
  // -----获取车位周同比
  const getParkingLotRise = () => {
    api.getParkingLotRise().then(res => {
      if (res.code === 200) {
        setParkingLotRise(res.result.data)
      }
    })
  }
  // -----获取车位日环比
  const getParkingLotFall = () => {
    api.getParkingLotFall().then(res => {
      if (res.code === 200) {
        if (res.result !== null && res.result !== '' && res.result !== undefined) {
          setParkingLotFall(res.result.data)
        }

      }
    })
  }
  // =========图表Api====================
  // 获取车流量图表数据
  const getParkingCharts = () => {
    api.getEtcCharts().then(res => {
      if (res.code === 200) {
        for (let i = 0; i < res.result.data.length; i++) {
          parkingChartsTit.push(res.result.data[i].time)
          parkingChartsVal.push(res.result.data[i].value)
        }
        parkingCharts();
      }
    })
  }
  // 获取ETC图表数据
  const getEtcCharts = () => {
    api.getEtcCharts().then(res => {
      if (res.code === 200) {
        for (let i = 0; i < res.result.data.length; i++) {
          EtcChartsTit.push(res.result.data[i].time)
          EtcChartsVal.push(res.result.data[i].value)
        }
        EtcCharts();
      }
    })
  }
  // 获取日收入趋势
  const getDailyIncome = () => {
    api.getDailyIncome().then(res => {
      if (res.code === 200) {
        for (let i = 0; i < res.result.data.length; i++) {
          dailyIncomeTit.push(res.result.data[i].time)
          dailyIncomeVal.push(res.result.data[i].value)
        }
        dailyIncome();
      }
    })
  }
  // 获取支付方式图表数据
  const getPaymentMethod = () => {
    api.getPaymentMethod().then(res => {
      if (res.code === 200) {
        paymentData = res.result.data
        PaymentMethod();
      }
    })
  }
  // 获取访问量图表数据
  const getVisits = () => {
    api.getVisits().then(res => {
      if (res.code === 200) {
        for (let i = 0; i < res.result.data.length; i++) {
          visitsTit.push(res.result.data[i].time)
          visitsVal.push(res.result.data[i].value)
        }
        visits();
      }
    })
  }
  return (
    <>
      <div className="index_wrap">
        {/* 顶部数据展示区 */}
        <div className="header_dataDispaly">
          <div className="dataDisplay_list">
            <p>总停车收入</p>
            <p>{totalRevenue.toLocaleString()}</p>
            <div className="Rise_fall_ratio">
              <span>周同比</span>
              <p className="rise"></p>
              <span>{rise}</span>
              <span>日环比</span>
              <p className="fall"></p>
              <span>{fall}</span>
              <div className="dayIncome">
                <div>日均停车收入<span>￥{dayIncome.toLocaleString()}</span></div>
              </div>
            </div>

          </div>
          <div className="dataDisplay_list">
            <p>车流量</p>
            <p>{totalFlow.toLocaleString()}</p>
            <div className="Rise_fall_ratio">
              {/* 车流量图表 */}
              <div className="flowCharts">
                <div id="parkingChart" style={{ width: '100%', height: '60px' }}></div>
              </div>
              <div className="dayVisits">
                <p>日访问量<span>{dayVisits.toLocaleString()}</span></p>
              </div>
            </div>
          </div>

          {/* 停车量表 */}
          <div className="dataDisplay_list">
            <p>ETC支付笔数</p>
            <p>{totalETC.toLocaleString()}</p>
            <div className="Rise_fall_ratio">
              <div className="etcChart">
                <div id="main" style={{ width: '100%', height: '60px' }}></div>
              </div>
              <div className="dayVisits">
                <p>使用率<span>{utilizationRate.toLocaleString()}</span></p>
              </div>
            </div>
          </div>

          {/* 车位占用率 */}
          <div className="dataDisplay_list">
            <p>车位占用率</p>
            <p>{occupancy}</p>
            <div className="Rise_fall_ratio">
              <div style={{ width: '95%', marginBottom: 20 }}>
                <Progress percent={parseFloat(occupancy)} trailColor='var(--color-primary-light-1)' />
              </div>
              <div className="dayVisits_con">
                <span>周同比</span>
                <p className="rise"></p>
                <span>{parkingLotRise}</span>
                <span>日环比</span>
                <p className="fall"></p>
                <span>{parkingLotFall}</span>
              </div>
            </div>
          </div>
        </div>


        {/* -------------------------------------------tab内容区 ------------------------------------------*/}
        <div className="tabs">
          <Tabs defaultActiveTab='1' onClickTab={onTable}>

            {/* 停车收入 */}
            <TabPane key='1' title='停车收入'>
              <Typography.Paragraph style={style}>
                <div className="dailyIncome">
                  <div id="dailyIncome" style={{ height: '400px' }}></div>
                  <div id="PaymentMethod" style={{ height: '400px' }}></div>
                </div>
                {/* 监控 */}
                <div className="monitor_wrap">

                  <ul className="monitor">
                    <Button type='primary' icon={<IconLeft />} />
                    <div className="monitor_con">
                      <li className="monitor_list">
                        <div className="monitor_list_left">
                          <p>入口A</p>
                          <p>车辆使用率</p>
                          <p>{monitor.monitorA}%</p>
                        </div>
                        {/* 监控画面 */}
                        <div className="monitor_list_right">
                          <Image
                            width={120}
                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                            alt='lamp'
                          />
                        </div>
                      </li>
                      <li className="monitor_list">
                        <div className="monitor_list_left">
                          <p>出口A</p>
                          <p>车辆使用率</p>
                          <p>{monitor.monitorA}%</p>
                        </div>
                        {/* 监控画面 */}
                        <div className="monitor_list_right">
                          <Image
                            width={120}
                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                            alt='lamp'
                          />
                        </div>
                      </li>
                      <li className="monitor_list">
                        <div className="monitor_list_left">
                          <p>入口B</p>
                          <p>车辆使用率</p>
                          <p>{monitor.monitorA}%</p>
                        </div>
                        {/* 监控画面 */}
                        <div className="monitor_list_right">
                          <Image
                            width={120}
                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                            alt='lamp'
                          />
                        </div>
                      </li>
                      <li className="monitor_list">
                        <div className="monitor_list_left">
                          <p>出口B</p>
                          <p>车辆使用率</p>
                          <p>{monitor.monitorA}%</p>
                        </div>
                        {/* 监控画面 */}
                        <div className="monitor_list_right">
                          <Image
                            width={120}
                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                            alt='lamp'
                          />
                        </div>
                      </li>
                      <li className="monitor_list">
                        <div className="monitor_list_left">
                          <p>入口C</p>
                          <p>车辆使用率</p>
                          <p>{monitor.monitorA}%</p>
                        </div>
                        {/* 监控画面 */}
                        <div className="monitor_list_right">
                          <Image
                            width={120}
                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                            alt='lamp'
                          />
                        </div>
                      </li>
                      <li className="monitor_list">
                        <div className="monitor_list_left">
                          <p>出口C</p>
                          <p>车辆使用率</p>
                          <p>{monitor.monitorA}%</p>
                        </div>
                        {/* 监控画面 */}
                        <div className="monitor_list_right">
                          <Image
                            width={120}
                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                            alt='lamp'
                          />
                        </div>
                      </li>
                    </div>

                    <Button type='primary' icon={<IconRight />} />
                  </ul>

                </div>

                {/* 实时数据 */}
                <div className="real_time_data">
                  <div id="realTimeData" style={{ height: '400px' }}></div>
                </div>
              </Typography.Paragraph>
            </TabPane>

            {/* 访问量 */}
            <TabPane key='2' title='访问量'>
              <Typography.Paragraph style={style}>
                <div className="visits_wrap">
                  <div id="visits" style={{ height: '400px' }}></div>
                </div>
              </Typography.Paragraph>
            </TabPane>
          </Tabs>
        </div>
      </div>
    </>
  )
}
export default Index